using System.Collections.Generic;
using System.Linq;
using System;

using SolutionOrchestrator.Validators;

namespace SolutionOrchestrator
{
	class RuleSet : IRuleSet
	{
		public RuleSet()
		{
			int q = 5;
		}

		volatile IEnumerable<IFileValidator> _validators;

		public IEnumerable<IFileValidator> All
		{
			get { return Validators.Concat(Doctors); }
		}

		readonly object _sync = new object();

		public IEnumerable<IFileValidator> Validators
		{
			get
			{
				if (_validators == null)
				{
					lock (_sync)
					{
						if (_validators == null)
						{
							_validators = GetAll<IFileValidator>().Select(x => (IFileValidator)Activator.CreateInstance(x)).ToArray();
						}
					}
				}
				return _validators;
			}
		}

		IEnumerable<Type> GetAll<T>()
		{
			return AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).Where(x => typeof(T).IsAssignableFrom(x) && !x.IsAbstract && x.IsClass);
		}

		IEnumerable<IFileDoctor> _doctors;

		public IEnumerable<IFileDoctor> Doctors
		{
			get
			{
				if (_doctors == null)
				{
					_doctors = GetAll<IFileDoctor>().Select(x => (IFileDoctor)Activator.CreateInstance(x));
				}
				return _doctors;
			}
		}
	}
}